package com.itfreer.sso.service;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.sso.share.entity.ResponseResult;
import com.itfreer.sso.share.service.ServiceTicketsValidateService;
import com.itfreer.utils.HeaderUtils;
import com.itfreer.utils.json.JsonUtils;
import com.itfreer.utils.sys.SystemParameter;

/**
 * ST验证
 */
@Component("RestServiceTicketsValidateService")
public class RestServiceTicketsValidateService implements ServiceTicketsValidateService {

	private final String validationUrl = "/serviceValidate";

	@Autowired
	private SystemParameter systemParameter;

	/**
	 * 验证
	 * 
	 * @param ticket
	 *            票据
	 * @param service
	 *            服务
	 * @param targetService
	 *            或是目标服务，传一个值就行
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked" })
	public ResponseResult validation(String ticket, String service, String targetService) throws Exception {
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target(systemParameter.getRemoteUrl() + validationUrl);
		Response response = target.queryParam("ticket", ticket).queryParam("service", service)
				.queryParam("targetService", targetService).request()
				.headers(HeaderUtils.getSysHeader(systemParameter.getsId(), systemParameter.getsPwd()))
				.buildGet().invoke();
		String msg = response.readEntity(String.class);
		Map<String, Object> map = null;
		if (msg.startsWith("{") && msg.endsWith("}")) {
			map = JsonUtils.toBean(msg, Map.class);
		} else {
			map = new HashMap<String, Object>();
			map.put("error", msg);
		}
		ResponseResult result = new ResponseResult(response.getStatus(), map);
		response.close();
		return result;
	}
}
